
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <thread>
#include <string>
#include <error.h>
#include <errno.h>
#include <string.h>
using namespace std;

string ToHex(pthread_t tid) // 十六进制
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%lx", tid);
    return buffer;
}

int gval = 100;
void *routine1(void *args)
{
    string name = static_cast<const char *>(args);
    while (true)
    {
        cout << "我是新线程,我的名字是:" << name << ",my tid is" << ToHex(pthread_self()) << ",全局变量(可修改): "<< gval << endl;
        gval++;
        sleep(1);
    }
    return 0;
}

void *routine2(void *args)
{
    string name = static_cast<const char *>(args);
    while (true)
    {
        cout << "我是新线程,我的名字是:" << name << ",my tid is" << ToHex(pthread_self()) << ",全局变量(只检测): "<< gval << endl;
        sleep(1);
        int* p  = nullptr;
        *p = 100;
    }
    return 0;
}

int main()
{
    pthread_t tid1;
    pthread_create(&tid1, nullptr, routine1, (void *)"thread-1");
    int n = pthread_join(tid1,nullptr);
    if(n != 0) //等待失败
    {
        cout << "join error" << " error :" << strerror(n) << endl;
    }
    cout << "join success" << endl;
    // pthread_t tid2;
    // pthread_create(&tid2, nullptr, routine2, (void *)"thread-2");
    // // pthread_t tid3;
    // // pthread_create(&tid3, nullptr, routine, (void *)"thread-3");
    // // pthread_t tid4;
    // // pthread_create(&tid4, nullptr, routine, (void *)"thread-4");
    // printf("新线程id:0x%lx \n", tid1);
    // printf("新线程id:0x%lx \n", tid2);
    // // printf("新线程id:0x%lx \n", tid3);
    // // printf("新线程id:0x%lx \n", tid4);
    // while (true)
    // {
    //     cout << "我是main线程" << endl;
    //     sleep(1);
    // }
    return 0;
}